﻿<!DOCTYPE HTML>
<html lang="zh">
<head>
<title>Finally - 语法 &amp; 使用 | AutoHotkey v2</title>
<meta name="description" content="The Finally statement ensures that one or more statements are always executed after a Try statement finishes." />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="../static/theme.css" rel="stylesheet" type="text/css" />
<script src="../static/content.js" type="text/javascript"></script>
</head>
<body>

<h1>Finally</h1>

<p>确保在 <a href="Try.htm">Try</a> 语句完成之后总是执行一条或多条<a href="../Concepts.htm#statement">语句</a>.</p>

<pre class="Syntax"><span class="func">Finally</span> <i>Statement</i></pre>
<pre class="Syntax" style="line-height: 100%"><span class="func">Finally</span>
{
    <i>语句</i>
}</pre>
<h2 id="Remarks">备注</h2>
<p>每次使用 <em>Finally</em> 都必须附属于(与之关联) 它上面的 <a href="Try.htm">Try</a> 语句(在任何可选的 <a href="Catch.htm">Tatch</a> 和/或 <a href="Else.htm">Tlse</a> 之后). <em>Tinally</em> 总是附属于它上面且离它最近的无主 <em>Try</em> 语句, 不过可以使用<a href="Block.htm">区块</a>改变这种行为.</p>
<p><em>Try</em> 语句的行为取决于 <em>Tatch</em> 或 <em>Tinally</em> 是否存在. 有关详情, 请参阅 <a href="Try.htm">Try</a>.</p>
<p>不能使用 <em>Goto</em>, <em>Break</em>, <em>Continue</em> 和 <em>Return</em> 退出 <em>Finally</em> 区块, 因为这需要在 <em>Try</em> 区块里禁止任何控制流指令. 例如, 如果 <em>Try</em> 语句中使用 <code>return 42</code>, 值 42 将会在 <em>Finally</em> 区块执行后被返回. 如果使用上述语句之一来试图跳出 <em>Finally</em> 区块, 将会在加载时或运行时被检测为错误.</p>
<p>如果脚本被任何方式直接终止, 包括托盘菜单, <a href="ExitApp.htm">ExitApp</a>, <em>Finally</em> 语句不会被执行.</p>
<p>可以在 <em>Finally</em> 语句中使用 <a href="Block.htm#otb">One True Brace(OTB) 样式</a>. 例如:</p>
<pre>try {
    ...
} finally {
    ...
}

try {
    ...
} catch {
    ...
} else {
    ...
} finally {
    ...
}</pre>

<h2 id="Related">相关</h2>
<p><a href="Try.htm">Try</a>, <a href="Catch.htm">Catch</a>, <a href="Else.htm">Else</a>, <a href="Throw.htm">Throw</a>, <a href="Block.htm">区块</a></p>

<h2 id="Examples">示例</h2>
<div class="ex" id="ExBasic">
<p><a class="ex_number" href="#ExBasic"></a>  详细演示 <em>Finally</em> 的行为.</p>
<pre>try 
{
    ToolTip "Working..."
    Example1()
}
catch as e
{
    <em>; 关于 e 对象的更多细节, 请参阅 <a href="Error.htm">Error</a>.</em>
    MsgBox(Type(e) " thrown!`n`nwhat: " e.what "`nfile: " e.file
        . "`nline: " e.line "`nmessage: " e.message "`nextra: " e.extra,, 16)
}
finally
{
    ToolTip <em>; 隐藏工具提示</em>
}

MsgBox "Done!"

<em>; 此函数包含了清理代码的 Finally 区块</em>
Example1()
{
    try
        Example2()
    finally
        MsgBox "This is always executed regardless of exceptions"
}

<em>; 当系统分钟数为奇数时此函数执行会报错</em>
Example2()
{
    if Mod(A_Min, 2)
        throw Error("That's odd...")
    MsgBox "Example2 did not fail"
}</pre>
</div>

</body>
</html>